// 与执行ls -l | sort -n +4 效果相同的程序
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>

int main(void) {
    pid_t childpid;
    int fd[2];      // 管道描述符
    int ret;

    if ((pipe(fd) == -1) && (childpid = fork()) == -1) {
        perror("Failed to setup pipeline");
        return -1;
    }

    // 子进程程序
    if (childpid == 0) {
        fprintf(stderr, "this is son!\n");
        // 将文件写入管道中, dup2用于重定向，此次将STDOUT_FILENO重定向到fd[1]，即管道pipe写中
        ret = dup2(fd[1], STDOUT_FILENO);
        if (ret == -1) {
            perror("Failed to redirect stdout of ls");
            //return -1;
        } else if (close(fd[0]) == -1 || close(fd[1]) == -1) {
            perror("Failed to close extra pipe descriptors on ls");
            //return -1;
        } else {
            execl("/bin/ls", "ls", "-l", NULL);
            perror("Failed to execc ls");
        }

        return 1;
    }
    
    sleep(1);
    // 父进程程序, 使用sort进行排序
    // if (childpid == 1) {
        fprintf(stderr, "this is parent!\n");
        // 从管道中读取数据，将fd[0]重定向到标准输入中
        ret = dup2(fd[0], STDIN_FILENO);
        if (ret == -1) {
            perror("Failed to redirect stdin of sort");
            //return -1;
        } else if (close(fd[0]) == -1 || close(fd[1]) == -1) {
            perror("Failed to close extra pipe descriptors on sort");
            //return -1;
        } else {
            ret = execl("usr/bin/sort", "sort", "-n", "+4", NULL);
            if(ret == -1) perror("Failed to exec sort");
        }

        return 1;
    // }

    //return 0;
}